module i2s_reciever #(
    parameter DATA_BITS = 24,
    parameter SLOT_BITS = 32
)(
    input  wire bclk,
    input  wire lrclk,
    input  wire sdata,
    input  wire rst_n,

    output reg  [23:0] ldata,
    output reg  [23:0] rdata,
    output reg         ldata_vld,
    output reg         rdata_vld
);
    // --- 两拍同步 WS 到 BCLK 域 ---
    reg lr_ff1, lr_ff2;
    always @(posedge bclk or negedge rst_n) begin
        if(!rst_n) begin
            lr_ff1 <= 1'b0;
            lr_ff2 <= 1'b0;
        end else begin
            lr_ff1 <= lrclk;   // 当前
            lr_ff2 <= lr_ff1;  // 上一拍
        end
    end
    wire ws            = lr_ff2;
    wire ws_rising     = (lr_ff1==1'b1) && (lr_ff2==1'b0); // 正确写法
    wire ws_falling    = (lr_ff1==1'b0) && (lr_ff2==1'b1);

    // --- 半帧内 bit 索引（0..31） ---
    reg [5:0] bit_index;
    always @(posedge bclk or negedge rst_n) begin
        if(!rst_n) begin
            bit_index <= 6'd0;
        end else if (ws_rising || ws_falling) begin
            bit_index <= 6'd0;
        end else if (bit_index == SLOT_BITS-1) begin
            bit_index <= 6'd0;
        end else begin
            bit_index <= bit_index + 6'd1;
        end
    end

    // --- 移位寄存器 ---
    reg [23:0] lshift, rshift;

    always @(posedge bclk or negedge rst_n) begin
        if(!rst_n) begin
            lshift <= 24'd0; rshift <= 24'd0;
            ldata  <= 24'd0; rdata  <= 24'd0;
            ldata_vld <= 1'b0; rdata_vld <= 1'b0;
        end else begin
            ldata_vld <= 1'b0;
            rdata_vld <= 1'b0;

            // I²S：bit_index==0 跳过（1bit 延时）
            if (bit_index >= 6'd1 && bit_index <= 6'd24) begin
                if (ws==1'b0) begin
                    // 左声道
                    if (bit_index < 6'd24) begin
                        lshift <= {lshift[22:0], sdata};
                    end else begin
                        // 最后一位，直接并入输出，避免非阻塞时序漏掉当拍位
                        ldata     <= {lshift[22:0], sdata};
                        ldata_vld <= 1'b1;
                    end
                end else begin
                    // 右声道
                    if (bit_index < 6'd24) begin
                        rshift <= {rshift[22:0], sdata};
                    end else begin
                        rdata     <= {rshift[22:0], sdata};
                        rdata_vld <= 1'b1;
                    end
                end
            end
        end
    end
endmodule


module from_24bit_to_16bit(
	input   wire    rst_n,
	input   wire    clk,
	input   wire    data_vld_in,
	input   wire[23:0]  data_in,
	output  reg     data_vld_out,
	output  reg [15:0]  data_out
);
	
	always @(posedge clk or negedge rst_n) begin
		if(!rst_n) begin
			data_out <= 16'd0;
			data_vld_out <= 1'b0;
		end
		else begin
			if(data_vld_in) begin
				data_out <= data_in[23:8]; //取高16位
				data_vld_out <= 1'b1;
			end
			else begin
				data_out <= 16'd0;
				data_vld_out <= 1'b0;
			end
		end
	end

endmodule
